<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2018/2/5
 * Time: 16:01
 */

namespace App\Http\Controllers\Api\Mp;


use App\Http\Controllers\Api\ApiBase;
use App\Http\Resources\User as UserResources;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class AuthController extends ApiBase
{
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|exists:users,email',
            'password' => 'required|between:5,32',
        ], [
            'username.required' => '请输入登录邮箱',
            'username.exists' => '登录邮箱不存在',
            'password.required' => '请输入密码',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $email = $request->input("username");
        $password = $request->input("password");
        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            $user = Auth::user();
            $data['user'] = new UserResources($user);
            $data['token'] = $user->createToken($user,['web-mp'])->accessToken;
            return $this->success($data);
        } else {
            return $this->failed('密码错误');
        }


    }

}